import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';
import router from '@/router';

export interface HttpResponse<T = unknown> {
  status: number;
  statusText: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}
axios.defaults.timeout = 9000;

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    if (
      config.url === '/api/productgrave/exportexcel' ||
      config.url?.includes('/api/analysis/exportExcelReport') ||
      config.url?.includes('/api/analysis/exportExcelAlarm')
    ) {
      config.responseType = 'blob';
    }
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    // console.log(`状态：-----${response.status}`);
    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      const res = response.data;
      const userStore = useUserStore();
      if (response.status === 401) {
        // userStore.logout();
      }

      // Message.error({
      //   content: res.statusText || 'Error',
      //   duration: 5 * 1000,
      // });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [401, 50012, 50014].includes(res.status) &&
        response.config.url !== '/admin/api/user/info'
      ) {
        // console.log('去登录');
        Modal.error({
          title: '信息',
          content: '您的登录已过期，请重新登录！',
          okText: '去登录',
          async onOk() {
            await userStore.logout();
            //  window.location.reload();
          },
        });
      } else if (res.status === 1) {
        return res;
      }
      return Promise.reject(new Error(res.statusText || 'Error'));
    }

    return response.data;
  },
  (error) => {
    // console.log(`error:${error.response.status}`)
    if (error.response.status === 401) {
      Message.error({
        content:
          '您的登录信息已过期，您可以取消以停留在此页，或重新登录' || 'Error',
        duration: 2 * 1000,
      });
      router.replace('/login');
    } else if (error.response.status === 403) {
      Message.error({
        content: '您没权限显示' || 'Error',
        duration: 2 * 1000,
      });
    } else if (error.response.status === 400) {
      Message.error({
        content: error.message || '客户端错误',
        duration: 3 * 1000,
      });
    } else if (error.response.status === 404) {
      Message.error({
        content: '网络请求不存在',
        duration: 3 * 1000,
      });
    } else if (error.response.status === 500) {
      Message.error({
        content: error.message || '服务器异常',
        duration: 3 * 1000,
      });
    } else {
      Message.error({
        content: error.message || 'Request Error',
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);
